import os

from fastapi import FastAPI
from pydantic import BaseModel

from enum import Enum

app = FastAPI()  # 创建一个fastapi的对象


class Item(BaseModel):  # 用于做数据校验
    name: str
    price: float
    is_offer: bool = True


class CustomEnum(str, Enum):  # 用于做路由配置
    first = "first"
    second = "second"


@app.get("/")
def read_root():
    return {"data": "hello world"}


@app.get("/items/{items_id}")  # items_id作为一个路由参数 q作为一个查询字符串参数,如果没有设置默认值,那么就是必传的
def read_items(items_id: int, q: str = None):
    return {"items_id": items_id, "q": q}


@app.put("/items/{items_id}")
def read_class_items(items_id: int, item: Item):  # item声明是一个Item对象,并且可以用于做数据校验
    return {"items_id": items_id, "name": item.name}


@app.get("/items/{items_id}/{url_path}")
def read_enum(items_id: int, url_path: CustomEnum):
    if url_path == CustomEnum.first:
        return {"items_id": items_id, "url_path": url_path}
    return {"items_id": items_id, "url_path": url_path}


@app.get("/items/{items_id}/{file_path:path}")
def read_file(items_id: int, file_path: str):
    return {"items_id": items_id, "file_path": file_path}


if __name__ == '__main__':
    os.system("uvicorn main:app --reload")
